package com.expdatacloud.controller.iqc;


import com.expdatacloud.annotation.AutoLog;
import com.expdatacloud.dto.ApiResponse;
import com.expdatacloud.entity.*;
import com.expdatacloud.mapper.IqcDetectionMapper;
import com.expdatacloud.service.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 检验明细表 前端控制器
 * </p>
 *
 * @author jie
 * @since 2019-11-14
 */
@RequestMapping("/iqcCheckItemDetails")
@Controller
@SuppressWarnings("all")
public class IqcCheckItemDetailsController {

    @Autowired
    private IqcCheckItemDetailsService iqcCheckItemDetailsService;
    @Autowired
    private ModelsMgtService modelsMgtService;
    @Autowired
    private InspectionPlanMgtService inspectionPlanMgtService;
    @Autowired
    private IqcDetectionService detectionService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private IqcSamplingShowService iqcSamplingShowService;
    @Autowired
    private IqcDetectionDetailService iqcDetectionDetailService;
    @Autowired
    private SampleMgtService sampleMgtService;
    @Autowired
    private SampleMgtDetailService sampleMgtDetailService;
    @Autowired
    private IqcDetectionMapper iqcDetectionMapper;

    /**
     * 去检验详情页面
     * 这个位置我也不想这么跳转的，没办法要加校验
     */
    @GetMapping("/toIqcCheckDetails")
    public String toIqcCheckDetails(String receiptKey, String sku,
                                    HttpServletRequest request,
                                    @CookieValue("library") String library,
                                    @SessionAttribute("users") String user) {

        iqcCheckItemDetailsService.sysToAddInspectionCategory(receiptKey, sku, user);
        //检测
        IqcDetection iqcDetectionParm = new IqcDetection();
        iqcDetectionParm.setSku(sku);
        iqcDetectionParm.setReceiptKey(receiptKey);
        IqcDetection iqcDetection = detectionService.getByReceiptkeyAndSku(iqcDetectionParm);
        //机型
        List<ModelsMgt> modelsMgtList = modelsMgtService.list(null);
        //检验方案集合
        List<InspectionPlanMgt> inspectionPlanMgtList = inspectionPlanMgtService.list();
        //根据货主 sku 查询  为了让下面显示默认的检验方案做准备
        Sku skuEntity = skuService.getBySkuStorerKey(iqcDetection.getSku(), iqcDetection.getShipper());
        if (skuEntity != null && skuEntity.getSusr4() != null) {
            if (iqcDetection.getInspectionCategory() != null && !"".equals(iqcDetection.getInspectionCategory())) {
                //根据检验品类查询 显示默认的检验方案，新单展示默认的，非新单展示保存后的检验方案
                InspectionPlanMgt inspectionPlanMgt2 = null;
                try {
                    inspectionPlanMgt2 = inspectionPlanMgtService.getByCheckCategory(skuEntity.getSusr4());
                } catch (Exception e) {
                    request.setAttribute("msg", "该单号存在两个默认检验方案，请完善信息后访问，点击返回iqc检测页面！");
                    return "iqc/iqcCheckItemDetails";
                }
                if (inspectionPlanMgt2 == null) {
                    request.setAttribute("msg", "检验方案管理表 ，checkCategory （检验品类） 为必填，请完善信息后访问，点击返回iqc检测页面！");
                    return "iqc/iqcCheckItemDetails";
                }
                //检验项目集合名称用来 默认检验方案选中的
                String checkScenarioName = getCheckScenarioName(iqcDetection, inspectionPlanMgt2);
                //带出待检数量 带出不合格数量累计
                double quarantineQuantity = getQuarantineQuantity(receiptKey, iqcDetection);
                //带出抽检数量
                SampleMgtDetail sampleMgtDetail = null;
                try {
                    sampleMgtDetail = sampleMgtDetailService.sampleMgtDetail(inspectionPlanMgt2.getSampleKey(), quarantineQuantity);
                } catch (Exception e) {
                    request.setAttribute("msg", "抽检数量为" + quarantineQuantity + "的在抽样基准管理中维护的范围存在多个，请去页面手动修改!");
                    return "iqc/iqcCheckItemDetails";
                }
                if (sampleMgtDetail == null) {
                    request.setAttribute("msg", "该数据在抽样基准管理表 查询不到，抽样水平编码为" + inspectionPlanMgt2.getSampleKey() + ",抽检数量为:" + quarantineQuantity + "，请完善信息后访问，点击返回iqc检测页面！");
                    return "iqc/iqcCheckItemDetails";
                }
                if (iqcDetection.getQuarantineQuantity() < sampleMgtDetail.getSample_Qty()) {
                    iqcDetection.setSamplingQuantity(iqcDetection.getQuarantineQuantity());
                } else {
                    iqcDetection.setSamplingQuantity(sampleMgtDetail.getSample_Qty());
                }
                request.setAttribute("library", library);
                request.setAttribute("modelsMgtList", modelsMgtList);
                request.setAttribute("iqcDetection", iqcDetection);
                request.setAttribute("inspectionPlanMgtList", inspectionPlanMgtList);
                request.setAttribute("inspectionPlanMgt2", inspectionPlanMgt2);
                request.setAttribute("checkScenarioName", checkScenarioName);
                return "iqc/iqcCheckItemDetails";
            }
        }

        request.setAttribute("msg", "susr4（SKU表的检验类别）为必填，请在检验品类管理进行设置，点击返回iqc检测页面！");
        return "iqc/iqcCheckItemDetails";

    }

    /**
     * 带出待检数量 带出不合格数量累计
     *
     * @param receiptKey
     * @param iqcDetection
     * @return
     */
    private double getQuarantineQuantity(String receiptKey, IqcDetection iqcDetection) {
        IqcDetectionDetail iqcDetectionDetail = new IqcDetectionDetail();
        iqcDetectionDetail.setSku(iqcDetection.getSku());
        iqcDetectionDetail.setReceiptKey(receiptKey);
        double quarantineQuantity = 0;
        double unqualifiedQuantity = 0;
        List<IqcDetectionDetail> iqcDetectionDetailList = iqcDetectionDetailService.list(iqcDetectionDetail);
        for (IqcDetectionDetail detectionDetail : iqcDetectionDetailList) {
            quarantineQuantity += detectionDetail.getQuarantineQuantity();
            unqualifiedQuantity += detectionDetail.getUnqualifiedQuantity();
        }
        iqcDetection.setQuarantineQuantity(quarantineQuantity);
        iqcDetection.setUnqualifiedQuantity(unqualifiedQuantity);
        return quarantineQuantity;
    }

    /**
     * 检验项目集合名称用来 默认检验方案选中的
     *
     * @param iqcDetection
     * @param inspectionPlanMgt2
     * @return 检验项目集合名称
     */
    private String getCheckScenarioName(IqcDetection iqcDetection, InspectionPlanMgt inspectionPlanMgt2) {
        String checkScenarioName;
        if (iqcDetection.getCheckScenarioName() != null) {
            checkScenarioName = iqcDetection.getCheckScenarioName();
        } else {
            checkScenarioName = inspectionPlanMgt2.getCheckScenarioName();
        }
        return checkScenarioName;
    }

    /**
     * 检验项目集合名称
     */
    @GetMapping("/checkItemDetails")
    @ResponseBody
    public ApiResponse checkItemDetails(String checkScenarioName, String receiptKey, String sku, HttpSession session) {
        String users = session.getAttribute("users").toString();
        //根据检验方案名称 ，查询检验项目集合名称查询
        String checkItemName = inspectionPlanMgtService.getCheckProjectKeyByCheckScenarioName(checkScenarioName);
        List<IqcCheckItemDetails> iqcCheckItemDetailsList = iqcCheckItemDetailsService.list(null, receiptKey, sku);
        //写入数据
        iqcCheckItemDetailsService.writeData(iqcCheckItemDetailsList, checkItemName, receiptKey, sku, users);
        return ApiResponse.ok(iqcCheckItemDetailsService.list(null, receiptKey, sku));
    }

    @AutoLog(title = "检验项目更新")
    @PostMapping(value = "/update", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String update(@RequestBody Object jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        IqcCheckItemDetails iqcCheckItemDetails2 = mapper.convertValue(jsonStr, IqcCheckItemDetails.class);
        IqcDetection iqcDetection = iqcDetectionMapper.getBySkuAndReceiptKey(iqcCheckItemDetails2.getSku(), iqcCheckItemDetails2.getReceiptKey());
        //获取前端传递过来的检验明细对象
        iqcCheckItemDetailsService.update(iqcCheckItemDetails2);
        iqcSamplingShowService.updateRejectedNumber(iqcCheckItemDetails2);
        return detectionService.getResult(iqcCheckItemDetails2.getReceiptKey(), iqcCheckItemDetails2.getSku());
    }

    /**
     * 获取检验结果
     */
    @GetMapping(value = "/getCheckResult")
    @ResponseBody
    public String getCheckResult(String receiptKey, String sku) {
        return detectionService.getResult(receiptKey, sku);
    }

}

